package com.carrot.ai.controller;

import com.carrot.ai.enums.ServiceType;
import com.carrot.ai.repository.ChatHistoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class CustomerServiceController {

    @Autowired
    private ChatHistoryRepository chatHistoryRepository;

    @Autowired
    private ChatClient serviceChatClient;

    @RequestMapping(value = "/service", produces = "text/html;charset=utf-8")
    public Flux<String> chat(@RequestParam(defaultValue = "讲个笑话") String prompt, @RequestParam String chatId) {

        // 保存会话id
        chatHistoryRepository.save(ServiceType.SERVICE, chatId);

        // 目前SpringAI的OpenAI客户端与阿里云百炼存在兼容性问题，所以FunctionCalling功能无法使用stream模式，这里使用call来调用
        return serviceChatClient
                .prompt(prompt) // 传入user提示词
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }
}
